<script setup lang="ts">
import { getCategoryAPI, getCategoryDetailAPI } from '@/services/category'
import type { CategoryItems, ProductInfo } from '@/types/category'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref } from 'vue'

const categoryListData = ref<CategoryItems[]>([])
const activeCategoryId = ref<number | null>(7) //默认选中第一个
const productQuantity = ref<number>(0) // 商品数量
const productList = ref<ProductInfo[]>([]) //存储根据分类ID获取到的商品列表
// 当前页码
let currentPage = 1
// 每页显示的数量
const pageSize = 10
// 标志位，用于判断是否还有更多数据
let hasMoreData = true
const getCategoryData = async () => {
  const res = await getCategoryAPI()
  categoryListData.value = res.data.info_list
  if (activeCategoryId.value === null && categoryListData.value.length > 0) {
    activeCategoryId.value = categoryListData.value[0].id
  }
}

// 在 onLoad 中初始化数据
onLoad(() => {
  /* 页面重载时默认选中第一个 */
  isActive(7)
  setActiveCategory(7)
  getCategoryData()
  getCategoryDetailData()
})
/* onMounted(() => {
    console.log(stock.value)
  }) */

// 在 onShow 中获取存储的 ID
onShow(() => {
  const id = uni.getStorageSync('activeCategoryId')
  if (id !== null) {
    activeCategoryId.value = parseInt(id)
  }
})

// 更新选中的分类
const setActiveCategory = async (categoryId: number) => {
  activeCategoryId.value = categoryId
  // 如果需要，可以将选中的 ID 存储到本地
  console.log(categoryId)

  uni.setStorageSync('activeCategoryId', categoryId.toString())
  const res = await getCategoryDetailAPI({
    page: '1',
    size: '10',
    is_online: '1',
    category: String(activeCategoryId.value), // 已经是字符串
  })
  if (res.code=="200") {
    productList.value=res.data
  }
  console.log(res)
  console.log(productList.value);

}

const isActive = (categoryId: number) => {
  return activeCategoryId.value === categoryId
}

// 测试根据分类id获取商品详情 页面默认开启的时候调用
const getCategoryDetailData = async () => {
  // 如果没有更多数据了，直接返回，不发起请求
  if (!hasMoreData) {
    return
  }
  const res = await getCategoryDetailAPI({
    page: String(currentPage),
    size: String(pageSize),
    category: String(activeCategoryId.value),
  })
  console.log(res)
  if (currentPage === 1) {
    //如果是第一页，直接赋值
    productList.value = res.data
  } else {
    //如果不是第一页，追加数据
    productList.value = [...productList.value, ...res.data]
  }
  //检查是否还有更多的数据
  if (res.data.length < pageSize) {
    hasMoreData = false
    console.log('没有更多数据了')
  }
}
// 判断商品库存是否为0
// const stock = productList.value?.spec[0].stock

// 减少商品数量 黄花鱼
const decreaseQuantity = () => {
  if (productQuantity.value > 0) {
    productQuantity.value--
    updateCart()
  }
}

const increaseQuantity = () => {
  productQuantity.value++
  updateCart()
}

// 更新购物车
const updateCart = () => {
  // 将数量更新同步到购物车或其他存储中
  console.log('商品数量更新:', productQuantity.value)
}
// 搜索方法
const navigatorToSearch = async () => {
  uni.navigateTo({
    url: '/pages/search/search',
  })
}
// 滚动刷新
const onscroll = () => {
  console.log('我到底部了啦')
  if (hasMoreData) {
    // 滚动到底部时，页码加1
    currentPage++
    // 重新调用获取数据的函数
    getCategoryDetailData()
  }
}
</script>

<template>
  <view class="viewport">
    <!-- 搜索框 -->
    <view class="search" @tap="navigatorToSearch">
      <view class="input">
        <text class="iconfont icon-sousuo">新鲜鸡翅</text>
      </view>
    </view>
    <!--    <view class="search">
      <view class="input">
        <text class="iconfont icon-sousuo"></text>
        <text class="search-input" placeholder="搜索商品">搜索</text>
        <text class="icon-scan"></text>
      </view>
    </view> -->
    <!-- 分类 -->
    <view class="categories">
      <!-- 左侧：分类目录 -->
      <scroll-view class="primary" scroll-y>
        <view
          v-for="item in categoryListData"
          :key="item.id"
          class="item"
          :class="{ active: isActive(item.id) }"
          @tap="setActiveCategory(item.id)"
        >
          <text class="name">{{ item.name }}</text>
        </view>
      </scroll-view>
      <!-- 右侧：内容 -->
      <scroll-view @scrolltolower="onscroll" class="secondary" scroll-y>
        <!-- 内容区域 -->
        <navigator
          v-for="item in productList"
          :key="item.id"
          :url="`/pages/goods/goods?id=${item.id}`"
          class="product-card"
          :class="{ 'sold-out': item.spec[0]?.stock === '0' }"
        >
          <view class="img-box">
            <img :src="item.pictureList[0]?.url || ''" :alt="item.name" class="product-image" />
          </view>

          <view class="product-info">
            <view class="product-details">
              <h3 class="product-title">{{ item.name }}</h3>
              <view class="product-description">
                <text>{{ item.mealdesc }}</text>
              </view>
            </view>
            <view class="product-price">
              <view class="price-info">
                <span class="current-price">¥{{ item.spec[0]?.price || 2.0 }}</span>
                <span class="soldoutText" v-if="item.spec[0]?.stock === '0'">已售罄</span>
              </view>
            </view>
          </view>
        </navigator>
      </scroll-view>
    </view>
  </view>
</template>

<style lang="scss">
page {
  height: 100%;
  overflow: hidden;
}

//商品卖完的样式

.viewport {
  height: 100%;
  display: flex;
  flex-direction: column;
}

// 搜索start
.search {
  padding: 0 30rpx 20rpx;
  background-color: #fff;

  .input {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 64rpx;
    padding-left: 26rpx;
    color: #8b8b8b;
    font-size: 28rpx;
    border-radius: 32rpx;
    background-color: #f3f4f4;
  }
}

.icon-search {
  &::before {
    margin-right: 10rpx;
  }
}

// 搜索end

/* 分类 */
.categories {
  flex: 1;
  min-height: 400rpx;
  display: flex;
}

/* 一级分类 */
.primary {
  overflow: hidden;
  width: 180rpx;
  flex: none;
  background-color: #f6f6f6;

  .item {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 96rpx;
    font-size: 26rpx;
    color: #595c63;
    position: relative;

    &::after {
      content: '';
      position: absolute;
      left: 42rpx;
      bottom: 0;
      width: 96rpx;
      border-top: 1rpx solid #e3e4e7;
    }
  }

  .active {
    background-color: #fff;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      width: 8rpx;
      height: 100%;
      background-color: #27ba9b;
    }
  }
}

.primary .item:last-child::after,
.primary .active::after {
  display: none;
}

/* 二级分类 */
.secondary {
  background-color: #efefef;
  padding: 20rpx;
  box-sizing: border-box;

  .carousel {
    height: 200rpx;
    margin: 0 30rpx 20rpx;
    border-radius: 4rpx;
    overflow: hidden;
  }

  .panel {
    margin: 0 30rpx 0rpx;
  }

  .title {
    height: 60rpx;
    line-height: 60rpx;
    color: #333;
    font-size: 28rpx;
    border-bottom: 1rpx solid #f7f7f8;

    .more {
      float: right;
      padding-left: 20rpx;
      font-size: 24rpx;
      color: #999;
    }
  }

  .more {
    &::after {
      font-family: 'erabbit' !important;
      content: '\e6c2';
    }
  }

  .section {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    padding: 20rpx 0;

    .goods {
      width: 150rpx;
      margin: 0rpx 30rpx 20rpx 0;

      &:nth-child(3n) {
        margin-right: 0;
      }

      image {
        width: 150rpx;
        height: 150rpx;
      }

      .name {
        padding: 5rpx;
        font-size: 22rpx;
        color: #333;
      }

      .price {
        padding: 5rpx;
        font-size: 18rpx;
        color: #cf4444;
      }

      .number {
        font-size: 24rpx;
        margin-left: 2rpx;
      }
    }
  }
}

.product-card {
  display: flex;
  // 用来设置商品遮罩
  position: relative;
  background-color: #fff;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin: 0 0 20rpx 0;
  width: 100%;
  height: 200rpx;
  // background-color: #27ba9b;
  padding: 20rpx;
  box-sizing: border-box;

  navigator {
    background-color: #fff;
  }

  .img-box {
    width: 160rpx;
    height: 160rpx;
    // background-color: #f0f0f0;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 20rpx;
    overflow: hidden;

    .product-image {
      width: 100%;
      height: 100%;
    }
  }

  .product-info {
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    // background-color: #cf4444;

    .product-details {
      width: 100%;
      flex: 1;
    }

    .product-title {
      font-size: 16px;
      font-weight: 600;
      // margin-bottom: 5rpx;
      color: #333;

      width: 250rpx;
      // background-color: #fff;
      white-space: nowrap; // 禁止换行
      overflow: hidden; // 超出部分隐藏
      text-overflow: ellipsis; // 超出部分显示省略号
    }
  }

  .product-description {
    font-size: 14px;
    color: #666;
    width: 250rpx;

    text {
      display: inline-block;
      // margin-bottom: 4px;
      width: 100%;
      // background-color: mediumvioletred;
      white-space: nowrap; // 禁止换行
      overflow: hidden; // 超出部分隐藏
      text-overflow: ellipsis; // 超出部分显示省略号

      font-size: 12px;
    }
  }

  .product-price {
    display: flex;
    justify-content: space-between;
    align-items: center;
    // background-color: blueviolet;
    width: 100%;
    height: 60rpx;
    // margin-top: auto;
    // padding-top: 10px;
    // border-top: 1px solid #eee;

    .price-info {
      // margin-right: 5rpx;
      .current-price {
        font-size: 16px;
        color: red;
      }

      .soldoutText {
        padding-left: 60px;
        font-size: 16px;
        color: #c0c0c0;
      }

      .original-price {
        font-size: 14px;
        color: #999;
        text-decoration: line-through;
        margin-left: 5px;
      }
    }

    .quantity-control {
      display: flex;
      align-items: center;
      width: 100%;
      width: 140rpx;

      // background-color: darkred;
      .quantity-btn {
        width: 32px;
        height: 26px;
        border: none;
        border-radius: 4px;
        background-color: #4caf50;
        color: white;
        font-size: 16px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        // margin-left: 8px;

        &.minus {
          background-color: #8bc34a;
        }
      }

      .quantity {
        // margin: 0 auto;
        font-size: 14px;
        color: #333;
        min-width: 24px;
        text-align: center;
      }
    }
  }
}

.sold-out {
  .product-info {
    .product-title {
      color: #a6a6a6;
    }
  }

  .product-description {
    color: #bebebe;
  }

  .product-price {
    .price-info {
      // margin-right: 5rpx;
      .current-price {
        color: #bebebe;
      }

      .soldoutText {
        color: #c0c0c0;
      }

      .original-price {
        color: #999;
      }
    }
  }
}

.product-card.sold-out::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #e0e0e0;
  /* 白色背景 */
  background-color: rgba(255, 255, 255, 0.7);
  z-index: 99;
  opacity: 0.7;
}

// 内容部分新布局end
</style>
